import re

from django_redis import get_redis_connection

from rest_framework import serializers
from rest_framework.settings import api_settings

from users.models import User


class CreateUserSerializer(serializers.ModelSerializer):
    """
    创建用户序列化器
    """
    # write_only负责输入 辅助校验
    password2 = serializers.CharField(label="确认密码", write_only=True)
    sms_code = serializers.CharField(label="短信确认码", write_only=True)
    allow = serializers.CharField(label="同意协议", write_only=True)

    # 补充token字段 read_only负责输出 要响应出去的字段
    token = serializers.CharField(label="登录状态token", read_only=True)

    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'password2', 'sms_code', 'mobile', 'allow', 'token')
        extra_kwargs = {
            'username': {
                'min_length': 5,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许5-20个字符的用户名',
                    'max_length': '仅允许5-20个字符的用户名',
                }
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            }
        }

    # 对单一字段进行验证
    def validte_mobile(self, value):
        """
        验证手机号
        :param value:
        :return:
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    # 对单一字段进行验证
    def validate_allow(self, value):
        """
        检验用户是否同意协议
        :param value:
        :return:
        """
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')
        return value

    # 对多字段校验
    def validate(self, data):
        print(data)
        """
        判断两次密码是否一致
        :param data:
        :return:
        """
        if data["password"] != data["password2"]:
            raise serializers.ValidationError("两次密码不一致")

        # 判断短信验证码
        redis_conn = get_redis_connection('verify_codes')
        mobile = data["mobile"]
        real_sms_code = redis_conn.get("sms_%s" % mobile)
        if real_sms_code is None:
            raise serializers.ValidationError("无效的短信验证码")
        if data["sms_code"] != real_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")
        return data

    def create(self, validated_data):
        """
        创建用户
        :param validated_data:
        :return:
        """
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]
        user = super().create(validated_data)

        # 调用django的认证系统加密码
        user.set_password(validated_data["password"])
        user.save()

        # 在响应user对象之前生成jwt_token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 将token和user绑定: 用于输出
        user.token = token
        return user
